<?

/*
*
*   Excalibur Content Management System
*   Copyright © 2008 Egor "Sontan" Kuryanovich
*
*   Based on Explay Engine v2.0 by Golovdinov Alexander
*
*   Official site: www.excms.ru
*   Contact e-mail: support@excms.ru
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
*/

if ($EXCMS != "work") {
	header ("Location: ../../index.php");
	exit;
}

if ($GLOBAL_USER['user_id'] > 0) {
// =====================================
$USER = $db->fetch_array ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = '".$GLOBAL_USER['user_id']."'"));
if ($USER['user_avatar'] == "") $avatar = "/images/avatars/noavatar.gif";
if ($USER['user_avatar'] != "") $avatar = "/images/avatars/".$USER['user_avatar'];
if ($USER['allow_comments'] == "on") $allow_comments = "checked";

$file = file ("modules/auth/admin/fields_options.txt");
$field = array ();

foreach ($file as $f) {
	$fld = explode ("|", $f);
	//print "{$fld[0]}|{$fld[1]}|{$fld[2]}|{$fld[3]}|{$fld[4]}|{$fld[5]}<br>";
	(isset($fld[2])) ? $field[$fld[0]] = $fld : $field[$fld[0]] = trim($fld[1]);
}

$form = "\n<form name=\"regist\" style=\"margin:0px\" action=\"\" method=\"POST\" enctype=\"multipart/form-data\">
<table cellspacing=\"2\" cellpadding=\"4\">";
if ($field['avatar'] == "on") {
	$form .= "<tr>
		<td valign=\"bottom\" align=\"right\" width=\"35%\">Аватар:</td>
		<td style=\"padding-left:10px\"><img src=\"$avatar\" title=\"{$USER['user_name']}\" alt=\"{$USER['user_name']}\" /></td>
	</tr>";
}
$form .= "<tr>
		<td align=\"right\">Имя<span style=\"color:red;\"><sup>*</sup></span>:</td>
		<td style=\"padding-left:10px\"><input class=\"form\" style=\"width:180px\" type=\"text\" name=\"name\" maxlength=\"30\" value=\"{$USER['user_name']}\" /></td>
	</tr>
	<tr>
		<td align=\"right\">E-mail<span style=\"color:red;\"><sup>*</sup></span>:</td>
		<td style=\"padding-left:10px\"><input class=\"form\" style=\"width:180px\" type=\"text\" name=\"email\" maxlength=\"30\" value=\"{$USER['user_email']}\" /></td>
	</tr>";

// =============================
if ($field['icq'] == "on") {
	$form .= "\n\t<tr>
		<td align=\"right\">ICQ:</td>
		<td style=\"padding-left:10px\"><input class=\"form\" style=\"width:180px\" type=\"text\" name=\"icq\" maxlength=\"15\" value=\"{$USER['user_icq']}\" /></td>
	</tr>";
}
if ($field['http'] == "on") {
	$form .= "\n\t<tr>
		<td align=\"right\">Сайт:</td>
		<td style=\"padding-left:10px\">http://<input class=\"form\" style=\"width:180px\" type=\"text\" name=\"http\" maxlength=\"40\" value=\"{$USER['user_http']}\" /></td>
	</tr>";
}
if ($field['avatar'] == "on") {
	 $form .= "\n\t<tr>
		<td align=\"right\" valign=\"top\">Аватар:</td>
		<td style=\"padding-left:10px\"><input class=\"form\" type=\"file\" name=\"image\" /></td>
	</tr>";
	if ($avatar != "/images/avatars/noavatar.gif") $form .= "\n\t<tr>
		<td align=\"right\">Удалить аватар:</td>
		<td style=\"padding-left:10px\"><input type=\"checkbox\" name=\"d_avatar\" value=\"true\" /></td>
	</tr>\n";	
}
if ($field['comments'] == "on") {
	$form .= "\n\t<tr>
		<td align=\"right\">Разрешить оставлять комментарии к профилю:</td>
		<td style=\"padding-left:10px\" valign=\"top\"><input type=\"checkbox\" name=\"allow_comments\" value=\"on\" $allow_comments /></td>
	</tr>";
}
// =============================
// 0 - name
// 1 - status
// 2 - type
// 3 - value (not for all)
// 4 - label
// 5 - important

for ($i=1; $i<=9; $i++) {
	if (trim($field['ad'.$i][1]) == "on") {
		$GLOBAL_USER['additional'.$i] = replace_symbols ($GLOBAL_USER['additional'.$i]);
		$GLOBAL_USER['additional'.$i] = str_replace ("&", "&amp;", $GLOBAL_USER['additional'.$i]);
		
		$form .= "\n\t<tr>\n\t\t<td align=\"right\" valign=\"top\">{$field['ad'.$i][4]}";
		if (trim($field['ad'.$i][5]) == "on") $form .= "<span style=\"color:red;\"><sup>*</sup></span>";
		$form .= ":</td>\n\t\t<td style=\"padding-left:10px\" valign=\"top\">";
		
		if ($field['ad'.$i][2] == "text") $form .= "\n\t\t\t<input type=\"text\" name=\"ad$i\" style=\"width:180px\" value=\"{$GLOBAL_USER['additional'.$i]}\" />";
		elseif ($field['ad'.$i][2] == "checkbox") ($GLOBAL_USER['additional$i'] == "1") ? $form .= "\n\t\t\t<input type=\"checkbox\" name=\"ad$i\" value=\"1\" checked />" : $form .= "\n\t\t\t<input type=\"checkbox\" name=\"ad$i\" value=\"1\" />";
		elseif ($field['ad'.$i][2] == "textarea") $form .= "\n\t\t\t<textarea name=\"ad$i\" rows=\"10\" cols=\"30\">{$GLOBAL_USER['additional'.$i]}</textarea>";
		elseif ($field['ad'.$i][2] == "select") {
			$form .= "\n\t\t\t<select name=\"ad$i\">";
			$values = explode ("<br>", $field['ad'.$i][3]);
			foreach ($values as $value) {
				($value == $GLOBAL_USER['additional'.$i]) ? $form .= "\n\t\t\t\t<option value=\"$value\" selected>$value</option>" : $form .= "\n\t\t\t\t<option value=\"$value\">$value</option>";
			}
			$form .= "\n\t\t\t</select>";
		}
		elseif ($field['ad'.$i][2] == "radio") {
			$values = explode ("<br>", $field['ad'.$i][3]);
			foreach ($values as $value) {
				($value == $GLOBAL_USER['additional'.$i]) ? $form .= "\n\t\t\t<input type=\"radio\" name=\"ad$i\" value=\"$value\" checked /> $value<br />" : $form .= "\n\t\t\t<input type=\"radio\" name=\"ad$i\" value=\"$value\" /> $value<br />";
			}
		}
		
		$form .= "\n\t\t</td>\n\t</tr>";
	}
}

	$form .= "\n<tr>
		<td colspan=\"2\" align=\"center\">
			<input type=\"submit\" name=\"save\" class=\"button\" value=\"Сохранить\" style=\"width:200px\" /><p />
			<small><span style=\"color:red;\">*</span> &mdash; обязательные для заполнения поля</small>
		</td>
	</tr>
</table></form>";	

$nname = strip_tags($_POST['name']);

$bad = array ("`","~","@","#","$","%","^","&","*","-","=","+","{","}",">","<",",","?","/","|");
$repl = array ("","","","","","","","","","","","","","","","","","","","");
$nname = str_replace ($bad, $repl, $nname);


$nemail = strip_tags($_POST['email']);
$nview = strip_tags($_POST['vemail']);
$nicq = strip_tags(trim($_POST['icq']));
$nicq = str_replace ("-", "", $nicq);
$nicq = str_replace (" ", "", $nicq);
$nhttp = strip_tags($_POST['http']);
$nhttp = str_replace ("http://", "", $nhttp);
$nschool = strip_tags($_POST['school']);
(isset ($_POST['allow_comments'])) ? $allow_comments = "on" : $allow_comments = "off";
if ($avatar != "/images/avatars/noavatar.gif") $file = $GLOBAL_USER['user_avatar'];
else $file = "";



if (isset($_POST['save'])) {
//-----------------------------
if ($_POST['name'] != "" && $_POST['email'] != "") {
	$error = "";	
	
	//==========================================================
	// 0 - name
	// 1 - status
	// 2 - type
	// 3 - value (not for all)
	// 4 - label
	// 5 - important
	$str = "";
	for ($i=1; $i<=9; $i++) {
		$ad = "";
		if (trim($field['ad'.$i][1]) == "on") {
			if ($field['ad'.$i][5] == "on" && (!isset($_POST['ad'.$i]) || strip_tags(trim($_POST['ad'.$i])) == "")) $error .= "<li>Не заполнено обязательное поле ".$field['ad'.$i][4]."!";
			else $ad = strip_tags(trim($_POST['ad'.$i]));
		}
		$str .= " , additional$i = '$ad' ";
	}
	//==========================================================
	
	$check_email = $db->query ("SELECT user_email FROM ".DB_PEREFIX."_users WHERE user_email = '$nemail' AND user_id != '".$GLOBAL_USER['user_id']."'");
	$check_name = $db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_name = '$nname' AND user_id != '".$GLOBAL_USER['user_id']."'");
	
	if (strlen($nname) < $SITE['user_name'] || strlen($nname) > 30) $error .= "<li>Имя должно быть от ".$SITE['user_name']." до 16 символов!";
	
	if ($db->num_rows($check_name) > 0) $error .= "<li>Пользователь с таким именем уже существует!";
	if ($db->num_rows($check_email) > 0) $error .= "<li>Пользователь с таким e-mail уже существует!";
	
	if (!eregi("^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}\$",$nemail)) $error .= "<li>Неправильный формат e-mail!";
		
	// ========================================
	if ($_FILES['image']['name'] != "") 
	{
		if ( copy($_FILES['image']['tmp_name'], "include/cache/".$_FILES['image']['name']) && 
			eregi('[а-яА-ЯA-Za-z0-9]\.(jpeg|jpg|gif|png|bmp|JPEG|JPG|GIF|PNG|BMP)', $_FILES['image']['name'])) 
		{
			if (save_image ("include/cache/".$_FILES['image']['name'], $GLOBAL_USER['user_id'])) 
				$file = $GLOBAL_USER['user_id'].".jpg";
			else 
				$error .= "\n<li>Ошибка загрузки изоображения (2)!"; 

		}				
		else 
			$error .= "\n<li>Ошибка загрузки изоображения (1)!";

		if (file_exists ("include/cache/".$_FILES['image']['name'])) unlink ("include/cache/".$_FILES['image']['name']);
	}
	// ========================================


	
	if ($_POST['d_avatar'] == 'true' && $avatar != '/images/avatars/noavatar.gif') 
	{
		if (mb_substr ($avatar, 0, 1) == '/') 
			$avatar = mb_substr ($avatar, 1, mb_strlen($avatar)-1);

		if ($db->query("UPDATE ".DB_PEREFIX."_users SET user_avatar = '' WHERE user_id = '$id'") && unlink($avatar)) 
		{ 
			$file = ''; 
			site_message ('Аватар удален'); 
		}
		else 
			$error .= '<li>Ошибка при удалении аватара!';
	}

	
	if ($error == '') 
	{
		$put_user = $db->query("UPDATE ".DB_PEREFIX."_users SET
			user_name = '$nname',
			user_email = '$nemail',
			user_icq = '$nicq',
			user_http = '$nhttp',
			user_avatar = '$file',
			allow_comments = '$allow_comments'
			$str WHERE user_id = '".$GLOBAL_USER['user_id']."'");
		
				
		if ($put_user) 
		{
			site_message ("Профиль сохранен!");
			$GLOBAL_USER = $db->fetch_array ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = '".$GLOBAL_USER['user_id']."'"));
			print_reg ();
		}
		else 
			site_error ("Ошибка сохранения профиля!");
	}
	else 
	{
		site_error ($error);
		if (file_exists("images/avatars/".$_FILES['avatar']['name'])) unlink ("images/avatars/".$_FILES['avatar']['name']);
		print_reg ();
	}
}
else 
{
	site_error ("Не заполнены необходимые поля!");
	print_reg ();
}
//-----------------------------
}
else print_reg ();
}
//===========================================
//===========================================
else site_error ("Ваш профиль не индентифицирован!");
function print_reg () {
	global $form, $GLOBAL_USER;
	past_table ("Редактирование профиля &mdash; ".$GLOBAL_USER['user_name'], $form);
}


function save_image ($src, $id) 
{
	global $SITE;
	
	if (!file_exists($src) || $src == "") return false;
	
	$name = "images/avatars/$id.jpg";
	
	if(eregi('[ёЁА-Яа-яA-Za-z0-9]\.(jpeg|jpg|JPEG|JPG)', $src)) 
		$thumbbase = imagecreatefromjpeg($src);
	elseif(eregi('[ёЁА-Яа-яA-Za-z0-9]\.(gif|GIF)', $src)) 
		$thumbbase = imagecreatefromgif($src);
	elseif(eregi('[ёЁА-Яа-яA-Za-z0-9]\.(png|PNG)', $src)) 
		$thumbbase = imagecreatefrompng($src);
	elseif(eregi('[ёЁА-Яа-яA-Za-z0-9]\.(bmp|wbmp|BMP|wbmp)', $src))
		$thumbbase = imagecreatefromwbmp($src);
	else 
		exit;
	
	$width = imagesx($thumbbase);
	$height = imagesy($thumbbase);
	
	// Определяем новый размер аватара
	if ($width > $SITE['max_avatar'] || $height > $SITE['max_avatar']) 
	{
		$k = max($width/$SITE['max_avatar'], $height/$SITE['max_avatar']);
		$new_width = intval($width / $k);
		$new_height = intval($height / $k);
	}
	else 
	{
		$new_width = $width;
		$new_height = $height;
	}
		
	// Создаем новый объект изображения
	$thumb = imagecreatetruecolor ($new_width, $new_height);
	// Переносим и сжимаем нужную часть загружаемого аватара
	imagecopyresampled($thumb, $thumbbase, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
	
	// Сохраняем в jpg
	if (imagejpeg($thumb, $name, 90)) 
	{
		imagedestroy($thumb);
		imagedestroy($thumbbase);
		@unlink ($src);
		return true;
	}
	return false;
}
?>
